/** @odoo-module **/
import {Component, onWillRender, toRaw} from "@odoo/owl";
import {standardFieldProps} from "@web/views/fields/standard_field_props";
import {registry} from "@web/core/registry";

export class CustomDataRenderer extends Component {
    setup() {
        this.jsonData = {l: [], r: [], list: {headers: [], rows: []}};
        onWillRender(() => this.formatData());
    }

    formatData() {
        const record = this.props.record;
        const name = this.props.name;
        if (!record || !name) {
            this.jsonData = {l: [], r: [], list: {headers: [], rows: []}};
            return;
        }
        let rawVal = toRaw(record.data[name]);
        if (!rawVal) {
            this.jsonData = {l: [], r: [], list: {headers: [], rows: []}};
            return;
        }
        if (typeof rawVal === "string") {
            try {
                rawVal = JSON.parse(rawVal);
            } catch {
                rawVal = {l: [], r: [], list: {headers: [], rows: []}};
            }
        }
        if (typeof rawVal === "object") {
            this.jsonData = {
                l: rawVal.l || [],
                r: rawVal.r || [],
                list: {
                    headers: rawVal.list?.headers || [],
                    rows: rawVal.list?.rows || [],
                },
            };
        } else {
            this.jsonData = {l: [], r: [], list: {headers: [], rows: []}};
        }
    }

    get readonly() {
        return this.props.readonly;
    }
}

// 註冊模板
CustomDataRenderer.template = "my_approval.CustomDataRenderer";
CustomDataRenderer.props = {...standardFieldProps};

// 註冊 field
registry.category("fields").add("custom_data_renderer", {component: CustomDataRenderer});
